#include "ipaddress.h"
#include "ui_ipaddress.h"

IPAddress::IPAddress(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::IPAddress)
{
    ui->setupUi(this);

    QList<QAbstractSpinBox*> spins = this->findChildren<QAbstractSpinBox*>();
    foreach(QAbstractSpinBox * spin, spins)
    {
        spin->clear();
        connect(spin, SIGNAL(valueChanged(QString)), this, SLOT(valueChanged(QString)));
        spin->installEventFilter(this);
//        connect(spin, SIGNAL(editingFinished()),this, SLOT(editingFinished()));
    }

    initWidget();
}

IPAddress::~IPAddress()
{
    delete ui;
}

// QSpinBox 获取焦点后选中全部内容
bool IPAddress::eventFilter(QObject *watched, QEvent *event)
{
    if(QEvent::FocusIn == event->type()) {
        QTimer::singleShot(0, this, [&, watched]() {
            QAbstractSpinBox *spin = (static_cast<QAbstractSpinBox *>(watched));
            spin->selectAll();
            spin->setFocus(Qt::TabFocusReason);
        });
    }
    return QWidget::eventFilter(watched,event);     // 最后将事件交给上层对话框
}

void IPAddress::clear()
{
    ui->ip1->clear();
    ui->ip2->clear();
    ui->ip3->clear();
    ui->ip4->clear();
    ip="";
    ui->ip1->setFocus();
}

QString IPAddress::getIP()
{
    ip = QString::number(ui->ip1->value())+"."+
            QString::number(ui->ip2->value())+"."+
            QString::number(ui->ip3->value())+"."+
            QString::number(ui->ip4->value());
    return ip;
}

void IPAddress::setIP(const QString &addr)
{
    //check if ip valid
    QRegExp regExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
    if (!regExp.exactMatch(addr)) {
        return;
    }
    if(ip != addr)
    {
        ip = addr;
        QStringList list = ip.split(".");
        ui->ip1->setValue(list.at(0).toInt());
        ui->ip2->setValue(list.at(1).toInt());
        ui->ip3->setValue(list.at(2).toInt());
        ui->ip4->setValue(list.at(3).toInt());
    }
}

void IPAddress::initWidget()
{
    ui->ip1->setFocus();
}

void IPAddress::valueChanged(const QString &text)
{
    int len = text.length();
    if(len == 3)
    {
        this->focusNextChild();
    }
    getIP();
}

void IPAddress::editingFinished()
{
    QString name = sender()->objectName();
    if(name == "ip1")
    {
        ui->ip2->setFocus();
    }
    else if (name == "ip2") {
        ui->ip3->setFocus();
    }
    else if (name == "ip3") {
        ui->ip4->setFocus();
    }
    else if (name == "ip4") {
        this->focusNextChild();
    }
}
